/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Clases;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author JULIAN
 */
public class Direccionamiento_login extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        Conexion.crearconexion();
        PreparedStatement st = null;
        SQL_Consultas obj = new SQL_Consultas();
                       
        try {
         String id = request.getParameter("usu");
         String pass = request.getParameter("pass");
         String caja ="";
         obj.SetDatos(id,pass);

        st=obj.GetLogin();

        ResultSet resultado = st.executeQuery();

        if(!resultado.next()){
                out.println("<html>");
                out.println("<head>");
                out.println("<title> :::AUTENTICACION FALLIDA!::: </title>");
                out.println("</head>");
                out.println("<body bgcolor='#000000'>");
                out.println("<table border='0' width='50%' align='center'>");
                out.println("</br>");
                out.println("</br>");
                out.println("</br>");
                out.println("</br>");
                out.println("</br>");
                out.println("</br>");
                out.println("</br>");
                out.println("</br>");
                out.println("</br>");
                out.println("</br>");
                out.println("</br>");
                out.println("</br>");
                out.println("<tr>");
                out.println("<td align='center'> <font face='Courier New, Courier, monospace' color='#000000' size='2'><font color=white>Autenticación erronea! Verifique que Usuario y Contraseña sean válidos<a href='index.jsp'>Regresar>></a></font></p></td></font>");
                out.println("</tr>");
                out.println("</table>");
                out.println("</body>");
                out.println("</html>");
                                 }
        else{

        int cargo = resultado.getInt("id_cargo");
        int almacen =resultado.getInt("id_almacen");
        HttpSession session = request.getSession(true);

         if (cargo == 4){

           st=obj.GetDatosEMP();
           resultado = st.executeQuery();
           resultado.next();

                session.setAttribute("id", Integer.toString(resultado.getInt("id_empleado")));
                session.setAttribute("nom", resultado.getString("nombres"));
                session.setAttribute("ape",  resultado.getString("apellidos"));
                session.setAttribute("tur",  resultado.getString("nombre_turno"));

                java.util.Date date = new java.util.Date();
                java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat("dd/MM/yyyy");
                String fecha = sdf.format(date);
                session.setAttribute("fini", fecha);

                session.setAttribute("tcot", resultado.getString("tipo_contrato"));
                session.setAttribute("sal",  Double.toString(resultado.getDouble("salario")));
                session.setAttribute("car",  resultado.getString("nombre_cargo"));
                session.setAttribute("alma", Integer.toString(resultado.getInt("id_almacen")));
           
           st=obj.GetExtrasEMP();
           resultado = st.executeQuery();


           if(!resultado.next()){
           session.setAttribute("extr","-1");
                                }
           else{              
           session.setAttribute("extr",Integer.toString(resultado.getInt("horas_extra")));

               }

                Conexion.cerrarconexion();
                resultado.close();                
                response.sendRedirect("DatosVen.jsp");

                      }
         else if (cargo == 2){
         session.setAttribute("alma",Integer.toString(almacen));
         response.sendRedirect("opcionesJP.jsp");
                             }

         else if (cargo == 3){

              caja =request.getParameter("caja");
              obj.setCaja(caja);
              st=obj.ValidaCaja();


              resultado=st.executeQuery();
              if(!resultado.next()){
                 out.println("<html>");
                 out.println("<title>ERROR</title>");
                 out.println("<Body Bgcolor=#000000>");
                 out.println("<p> <font color=white>almacenesbasedatos.no-ip.infoLa caja no existe</p></font>");
                 out.println("<input type=button style=Position:Absolute; left:20%; top:30% value=Regresar opciones gerencia onClick= window.location.href='Cerrar.jsp'>");
                 out.println("</html>");

                                   }

              else{

               int almacencaja=resultado.getInt("id_almacen");

               if(almacencaja!=almacen){
                  out.println("<html>");
                  out.println("<title>ERROR</title>");
                  out.println("<Body Bgcolor=#000000>");
                  out.println("<p><font color=white>usted no puede acceder a las cajas de este almacen</p></font>");
                  out.println("<input type=button style=Position:Absolute; left:20%; top:30% value=Regresar opciones gerencia onClick= window.location.href='Cerrar.jsp'>");
                  out.println("</html>");
                                       }
                      else{

                        caja =request.getParameter("caja");

                        SQL_Inserciones obj2 = new SQL_Inserciones();

                        obj2.setIdcaja(caja);
                        obj2.setIdCajero(request.getParameter("usu"));

                        st = obj2.InsertCajero();
                        st.executeUpdate();

                        session.setAttribute("alma",Integer.toString(almacen));
                        session.setAttribute("caja",caja);

                        response.sendRedirect("Venta.jsp");
                          }


         resultado.close();
                    }
                                 }
         else if (cargo == 1){
                   response.sendRedirect("OpcionesGerente.jsp");
                             }
            }


        } finally {
            st.close();            
            obj.cierrast();
            out.close();
            /*prueba*/
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(Direccionamiento_login.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(Direccionamiento_login.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>


}
